package com.webdemo04.action;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.webdemo04.util.DBHandler;
import com.webdemo04.bean.User;

@Namespace(value = "/jsp")
@Action(value = "UpdateUser", results = {
		@Result(name = "updateui", location = "/WEB-INF/jsp/update.jsp"),
		@Result(location = "QueryUser", type = "redirectAction") })
public class UpdateUser extends ActionSupport {

	private static final long serialVersionUID = 1L;
	private int id;
	private String flag;
	private User user;
	@Override
	public String execute() throws Exception {
		Connection conn = DBHandler.newInstance().getConnection();
		PreparedStatement pstmt = null;
		String sql = null;
		if("update".equals(flag)){
			sql = "update annotation01_user set name=? where id=?";
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, user.getName());
			pstmt.setInt(2, user.getId());
			pstmt.executeUpdate();
			return SUCCESS;
		}else{
			sql = "select id,name from annotation01_user where id=?";
			pstmt = conn.prepareStatement(sql);
			pstmt.setInt(1, id);
			ResultSet rs = pstmt.executeQuery();
			User user = null;
			if(rs.next()){
				user = new User();
				user.setId(rs.getInt("id"));
				user.setName(rs.getString("name"));
			}
			ActionContext.getContext().put("user", user);
			return "updateui";
		}
		
	}
	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getFlag() {
		return flag;
	}

	public void setFlag(String flag) {
		this.flag = flag;
	}

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	

}
